package org.example.project.bookstore.interpector;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.config.JwtConfig;
import org.example.handler.UserNotFoundException;
import org.example.project.bookstore.service.impl.UserServiceImpl;
import org.example.util.ResultTool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * @Auther:Liu
 * @Testname:IsLoginInterceptor
 * @Date:2025/8/19 18:04
 */
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            throw new UserNotFoundException("后端令牌数据不存在");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String s = ops.get(userService.LOGIN_PREFIX + userId);
        if (s == null) {
            throw new UserNotFoundException("后端令牌数据不存在");
        }
        if (!Objects.equals(s, token)) {
            throw new UserNotFoundException("后端令牌数据不存在");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
